package com.assa.ws.client.notify;

import java.io.FileInputStream;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import junit.framework.TestCase;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

import com.grupoassa.utils.IdGenerator;
import com.grupoassa.utils.XmlUtils;

@ContextConfiguration(locations = { "classpath:com/assa/spring/config/config.xml" })
public class NotifyClientTestCase extends AbstractJUnit4SpringContextTests {

	private static Logger logger = Logger.getLogger(NotifyClientTestCase.class.getName());

	static String NOTIFY_EVENT = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:a=\"http://www.w3.org/2005/08/addressing\"><s:Header><a:Action s:mustUnderstand=\"1\">http://docs.oasis-open.org/wsn/bw-2/NotificationConsumer/Notify</a:Action><VsDebuggerCausalityData xmlns=\"http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink\">uIDPo/R/1gon4KhAiaztK0ghOy0AAAAA+PP+iS7fFkSb1F8XlqSTQjxusP1PBRVAlo02dwpc8skACQAA</VsDebuggerCausalityData><a:To s:mustUnderstand=\"1\">http://127.0.0.1:8090/mockWSNServicePointNotificationBrokerPortBinding</a:To></s:Header><s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Notify xmlns=\"http://docs.oasis-open.org/wsn/b-2\"><NotificationMessage><Topic topns:dummy=\"\" Dialect=\"http://docs.oasis-open.org/wsn/t-1/TopicExpression/Simple\" xmlns:topns=\"http://www.ibmcompany.com/wsn_topic_space\">topns:cei_wsn_topic</Topic><Message><CommonBaseEvents xmlns=\"http://www.ibm.com/AC/commonbaseevent1_0_1\"><CommonBaseEvent version=\"1.0.1\" globalInstanceId=\"d40739f18dfc463797085fc41394eb8e\" extensionName=\"mortgageLendingProcessStart\" creationTime=\"2009-10-01T23:35:57.625-03:00\" sequenceNumber=\"1\"><sourceComponentId component=\"TestComponent\" subComponent=\"TestSubComponent\" componentIdType=\"TestComponentIdType\" application=\"TestApplication\" location=\"TestLocation\" locationType=\"IPV4\" componentType=\"TestComponentType\"/><situation categoryName=\"StartSituation\"><situationType xsi:type=\"StartSituation\" reasoningScope=\"EXTERNAL\" successDisposition=\"SUCCESSFUL\" situationQualifier=\"START_COMPLETED\"/></situation><mor:mortgageLendingProcessStart mor:eventName=\"mortgageLendingProcessStart\" xmlns:mor=\"http://MortgageLendingBAMModel\"><mor:loanNumber>12345</mor:loanNumber><mor:loanOfficer>Hernan</mor:loanOfficer><mor:dateStarted>2009-10-01T23:34:47</mor:dateStarted><mor:dateCompleted>2009-10-01T23:34:47</mor:dateCompleted></mor:mortgageLendingProcessStart></CommonBaseEvent></CommonBaseEvents></Message></NotificationMessage></Notify></s:Body></s:Envelope>";
	private static NotifyClient client;

	@BeforeClass
	public static void initVelocity() throws Exception {
		Velocity.init();

	}

	@Before
	public void initClient() {
		if(client == null) {
			client = (NotifyClient) this.applicationContext.getBean("notifyClient");			
		}

	}
	

	@Ignore
	public void notifyEventFromString() {
		try {
			String output = client.notifyEvent(NOTIFY_EVENT);
			logger.info(output);
		} catch (Exception e) {
			logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
			TestCase.fail();
		}
	}

	@Ignore
	public void notifyEventFromFile() {
		try {
			String input = XmlUtils.removeSpecialCharacters(readFile("./Untitled2.xml"));
			logger.info("Entrada : " + input);
			String output = client.notifyEvent(input);
			logger.info(output);
		} catch (Exception e) {
			logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
			TestCase.fail();
		}

	}
	
	@Test
	public void notifyEventFromVelocity() {
		try {
			String input = buildVelocityTemplate();
			logger.info("Entrada : " + input);
			String output = client.notifyEvent(input);
			logger.info(output);
		} catch (Exception e) {
			logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
			TestCase.fail();
		}
	}
	
	private String buildVelocityTemplate() throws Exception {
		Template template = Velocity.getTemplate("./creacionOrdenEvent.vm");
		VelocityContext context = new VelocityContext();
		context.put("instanceID", IdGenerator.getGlobalInstanceId());
		context.put("comprador", "Kiko");
		context.put("numeroOrden", "1211");
		context.put("cantidad", "15");
		StringWriter output = new StringWriter();
		template.merge(context, output);
		return XmlUtils.removeSpecialCharacters(output.toString());
	}

	private static String readFile(String file) {
		try {
			FileInputStream fi = new FileInputStream(file);
			StringBuffer sb = new StringBuffer();
			byte buffer[] = new byte[1000];
			int i = 0;
			while ((i = fi.read(buffer)) > 0) {
				sb.append(new String(buffer, 0, i, "UTF-8"));
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}



}
